package com.atguigu.flink.state;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/12/17
 * 
 * 计算每种传感器的水位和
 *  ReducingState； 聚合的类型和输出的类型一致！
 *
 *
 */
public class Demo5_ReducingState
{
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {

                       private ReducingState<Integer> sumVc;

                       @Override
                       public void open(Configuration parameters) throws Exception {

                           sumVc = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>("sumVc", new ReduceFunction<Integer>()
                           {
                               @Override
                               public Integer reduce(Integer value1, Integer value2) throws Exception {
                                   return value1 + value2;
                               }
                           }, Integer.class));

                       }

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                         //放入状态，自动聚合
                            sumVc.add(value.getVc());

                            //取出聚合的结果
                           out.collect(ctx.getCurrentKey() + ":"+sumVc.get());

                       }
                   })
                   .print();
        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
